import { useEffect, useRef, useState } from "react";

const Map = () => {
    const [searchIpt, setSearchIpt] = useState("餐厅");
    const [start, setStart] = useState("郑州市天健湖公园");
    const [end, setEnd] = useState("郑州大学");
    const m1 = useRef();// 获取dom容器
    const bd = useRef();// 缓存一个普通的变量,地图的信息都存入到bd中
    // 1-绘制地图的函数
    const drawMap = () => {
        bd.map = new window.BMapGL.Map(m1.current);          // 创建地图实例 
        bd.point = new window.BMapGL.Point(116.404, 39.915);  // 创建点坐标 
        bd.map.centerAndZoom(bd.point, 15);                 // 初始化地图，设置中心点坐标和地图级别
        bd.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
        createMyPos()




        // 获取当前地理位置:
        var geolocation = new window.BMapGL.Geolocation();
        geolocation.getCurrentPosition(function (r) {
            if (this.getStatus() == window.BMAP_STATUS_SUCCESS) {
                var mk = new window.BMapGL.Marker(r.point);
                bd.map.addOverlay(mk);
                bd.map.panTo(r.point);
                alert('您的位置：' + r.point.lng + ',' + r.point.lat);
            }
            else {
                alert('failed' + this.getStatus());
            }
        });
    }

    // 2- 创建当前的位置
    const createMyPos = () => {
        // 覆盖物!!
        // 创建带高度的点
        // var marker3d = new window.BMapGL.Marker3D(bd.point, 8000, {
        //     size: 50,
        //     shape: window.BMAP_SHAPE_CIRCLE,
        //     fillColor: '#f00',
        //     fillOpacity: 1
        // });
        // // 将点添加到地图上
        // bd.map.addOverlay(marker3d);
        var marker = new window.BMapGL.Marker(bd.point);        // 创建标注   
        bd.map.addOverlay(marker);
    }

    // 3- 搜索周边
    const search = () => {
        // 搜索前 把上一次的标记点去掉
        bd.map.clearOverlays();
        // bd.map.centerAndZoom(bd.point, 15);
        var local = new window.BMapGL.LocalSearch(bd.map, {
            renderOptions: { map: bd.map, autoViewport: true }
        });
        local.searchNearby(searchIpt, bd.point);
        // 加上当前位置的点
        createMyPos()
    }

    // 4- 路线规划
    const walk = () => {
        bd.map.centerAndZoom(bd.point, 15);
        var walk = new window.BMapGL.WalkingRoute(bd.map,
            { renderOptions: { map: bd.map, autoViewport: true } });
        walk.search(start, end);
    }

    useEffect(drawMap, []);
    return (
        <>
            <h1>百度地图的使用</h1>
            <hr />
            <input type="text" placeholder="搜索餐厅??" value={searchIpt} onChange={e => setSearchIpt(e.target.value)} /> <button onClick={search}>搜索</button> <br />
            <input type="text" placeholder="起点" value={start} onChange={e => setStart(e.target.value)} />
            <input type="text" placeholder="终点" value={end} onChange={e => setEnd(e.target.value)} /> <button onClick={walk}>搜索</button>
            <div ref={m1} style={{ height: '80vh', border: '2px solid red' }}></div>
        </>
    )
}
export default Map;